#include "pathfinding_graph.h"
#include <QDebug>

namespace application {

void PathfindingGraph::addNode(const GraphNode& node) {
    nodes_.append(node);
    rebuildIndexMap();
}

void PathfindingGraph::addEdge(const GraphEdge& edge) {
    edges_.append(edge);
}

void PathfindingGraph::markAvoidWait(const QString& nodeId, bool avoid) {
    auto it = nodeIndexMap_.find(nodeId);
    if (it == nodeIndexMap_.end()) {
        return;
    }
    int index = it.value();
    if (index >= 0 && index < nodes_.size()) {
        nodes_[index].avoidWait = avoid;
    }
}

const GraphNode* PathfindingGraph::findNode(const QString& nodeId) const {
    if (nodeIndexMap_.contains(nodeId)) {
        int index = nodeIndexMap_.value(nodeId);
        if (index >= 0 && index < nodes_.size()) {
            return &nodes_[index];
        }
    }
    return nullptr;
}

QVector<GraphEdge> PathfindingGraph::getEdgesFromNode(const QString& nodeId) const {
    QVector<GraphEdge> result;
    for (const auto& edge : edges_) {
        if (edge.fromNodeId == nodeId) {
            result.append(edge);
        }
    }
    return result;
}

QVector<GraphEdge> PathfindingGraph::getEdgesToNode(const QString& nodeId) const {
    QVector<GraphEdge> result;
    for (const auto& edge : edges_) {
        if (edge.toNodeId == nodeId) {
            result.append(edge);
        }
    }
    return result;
}

bool PathfindingGraph::hasNode(const QString& nodeId) const {
    return nodeIndexMap_.contains(nodeId);
}

bool PathfindingGraph::hasEdge(const QString& fromId, const QString& toId) const {
    for (const auto& edge : edges_) {
        if (edge.fromNodeId == fromId && edge.toNodeId == toId) {
            return true;
        }
    }
    return false;
}

void PathfindingGraph::clear() {
    nodes_.clear();
    edges_.clear();
    nodeIndexMap_.clear();
}

void PathfindingGraph::rebuildIndexMap() {
    nodeIndexMap_.clear();
    for (int i = 0; i < nodes_.size(); ++i) {
        nodeIndexMap_.insert(nodes_[i].id, i);
    }
}

} // namespace application
